import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Cascader,
  Col,
  Drawer,
  Form,
  Input,
  Row,
  Select,
  Space,
  Spin,
  Tabs,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import terminalService, {
  type PageListReq,
} from "@/api/services/qms/terminalService";
import workshopService from "@/api/services/mes/workshopService";
import postService from "@/api/services/system/postService";
import type { QmsInspectionTerminal } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import QmsInspectionTerminalItemPage, {
  type QmsInspectionTerminalItemHandles,
} from "./item";
import CustomTable from "@/components/grid/CustomTable";

const { TextArea } = Input;

export default function QmsInspectionTerminalPage() {
  const itemRef = useRef<QmsInspectionTerminalItemHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    name: undefined,
    ip: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<QmsInspectionTerminal[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<QmsInspectionTerminal | null>(
    null
  );
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);
  const [workshopTreeList, setWorkshopTreeList] = useState<MesWorkshop[]>([]);
  const [postOptions, setPostOptions] = useState<
    { value: React.Key; label: string }[]
  >([]);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  useEffect(() => {
    fetchWorkshopTreeList();
    fetchPostList();
  }, []);

  const columns: ColumnsType<QmsInspectionTerminal> = [
    {
      title: "编码",
      width: 120,
      key: "code",
      dataIndex: "code",
    },
    {
      title: "名称",
      width: 120,
      key: "name",
      dataIndex: "name",
    },
    {
      title: "车间",
      width: 120,
      key: "workshopName",
      dataIndex: "workshopName",
    },
    {
      title: "产线",
      width: 120,
      key: "lineName",
      dataIndex: "lineName",
    },
    {
      title: "工位",
      width: 120,
      key: "stationName",
      dataIndex: "stationName",
    },
    {
      title: "岗位",
      width: 120,
      key: "postName",
      dataIndex: "postName",
    },
    {
      title: "设备IP",
      width: 120,
      key: "ip",
      dataIndex: "ip",
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    terminalService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  //加载岗位列表
  const fetchPostList = async () => {
    try {
      const posts = await postService.list();
      const options = posts.map((post) => ({
        value: post.id,
        label: post.postName,
      }));
      setPostOptions(options);
    } catch (error) {
      console.error("获取岗位列表失败:", error);
      toast.error("获取岗位列表失败");
      return [];
    }
  };

  //加载树形结构数据
  const fetchWorkshopTreeList = async () => {
    await workshopService
      .treeList(queryParams)
      .then((data) => {
        if (data) {
          setWorkshopTreeList(data);
        }
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (qmsInspectionTerminal: QmsInspectionTerminal) => {
    setEditingData(qmsInspectionTerminal);
    form.setFieldsValue({
      ...qmsInspectionTerminal,
      workshopLineStation: [
        qmsInspectionTerminal.workshopId,
        qmsInspectionTerminal.lineId,
        qmsInspectionTerminal.stationId,
      ],
    });
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (qmsInspectionTerminal: QmsInspectionTerminal) => {
    setEditingData(qmsInspectionTerminal);
    form.setFieldsValue(qmsInspectionTerminal);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: QmsInspectionTerminal) => {
    try {
      setSubmitLoading(true);

      const [workshopId, lineId, stationId] = values.workshopLineStation || [];

      //检测终端不良采集项目
      const deleteItemIds = itemRef.current?.getDeleteIds();
      const addItems = itemRef.current?.getAddList();
      const updateItems = itemRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        workshopId,
        lineId,
        stationId,
        deleteItemIds: deleteItemIds,
        addItems: addItems,
        updateItems: updateItems,
      };
      if (editingData) {
        await terminalService.update(data);
        toast.success("更新质量检测终端 成功");
      } else {
        await terminalService.add(data);
        toast.success("创建质量检测终端 成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await terminalService.remove(selectedRowKeys);
      toast.success("删除质量检测终端 成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const cascaderOptions = workshopTreeList.map((workshop) => ({
    value: workshop.id,
    label: workshop.name,
    children: (workshop.children || []).map((line) => ({
      value: line.id,
      label: line.name,
      children: (line.children || []).map((station) => ({
        value: station.id,
        label: station.name,
      })),
    })),
  }));

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            const [workshopId, lineId, stationId] =
              values.workshopLineStation || [];
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              workshopId,
              lineId,
              stationId,
              page: 1,
            }));
          }}
        >
          <Form.Item name="name" label="名称">
            <Input placeholder="请输入名称" allowClear />
          </Form.Item>
          <Form.Item
            label="车间/产线/工位"
            name="workshopLineStation"
            rules={[{ required: true, message: "请选择车间/产线/工位" }]}
          >
            <Cascader
              options={cascaderOptions}
              placeholder="请选择车间/产线/工位"
              allowClear
              changeOnSelect={false}
              style={{ width: 230 }}
            />
          </Form.Item>
          <Form.Item name="ip" label="设备IP">
            <Input placeholder="请输入设备IP" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑质量检测终端 " : "新增质量检测终端 "}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item name="code" label="编码">
                <Input placeholder="请输入编码" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="名称"
                rules={[{ required: true, message: "请填写名称" }]}
              >
                <Input placeholder="请输入名称" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="车间/产线/工位"
                name="workshopLineStation"
                rules={[{ required: true, message: "请选择车间/产线/工位" }]}
              >
                <Cascader
                  options={cascaderOptions}
                  placeholder="请选择车间/产线/工位"
                  allowClear
                  changeOnSelect={false}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="postId" label="岗位">
                <Select
                  showSearch
                  options={postOptions}
                  placeholder="请选择岗位"
                  allowClear
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="ip"
                label="设备IP"
                rules={[
                  { required: true, message: "请填写设备IP" },
                  {
                    pattern:
                      /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/,
                    message: "请输入有效的IP地址",
                  },
                ]}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
              >
                <Input placeholder="请输入设备IP" allowClear />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={24}>
              <Form.Item
                name="remark"
                label="备注"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
              >
                <TextArea />
              </Form.Item>
            </Col>
          </Row>
          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "采集项目",
                children: (
                  <QmsInspectionTerminalItemPage
                    ref={itemRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>
    </Spin>
  );
}
